package com.macro.mall.tiny.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.macro.mall.tiny.domain.LoginUser;
import com.macro.mall.tiny.domain.User;
import com.macro.mall.tiny.mapper.ResourceMapper;
import com.macro.mall.tiny.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户信息
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user=userMapper.selectOne(queryWrapper);
        //如果没有查询到用户就抛出
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }

        //  查询对应权限信息
        List<String> permissions=resourceMapper.selectUrlByUserId(user.getId());

        //把数据封装成UserDetails返回
        return new LoginUser(user,permissions);
    }
}
